package com.ygqh.baby.controller.admin;

import com.fasterxml.jackson.core.type.TypeReference;
import com.ygqh.baby.ao.CommitStatus;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.QueryInfo;
import com.ygqh.baby.ao.ResultSet;
import com.ygqh.baby.constant.RedisConstant;
import com.ygqh.baby.controller.utils.DocumentHandler;
import com.ygqh.baby.controller.utils.ExcelUtil;
import com.ygqh.baby.handler.SkuExcelHandler;
import com.ygqh.baby.handler.WdtOrderExcelHandler;
import com.ygqh.baby.model.SkuExcelModel;
import com.ygqh.baby.model.WdtOrderImportExcelModel;
import com.ygqh.baby.model.WholesaleSkuModel;
import com.ygqh.baby.po.YgWholesaler;
import com.ygqh.baby.po.YgWholesalerPrebillRecord;
import com.ygqh.baby.po.YgWholesalerRechargeRecord;
import com.ygqh.baby.po.YgWholesalerSku;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.*;
import com.ygqh.baby.utils.JsonUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.poi.ss.usermodel.Row;
import org.crazycake.shiro.SerializeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author: sunshuo
 * @date: 2018/12/11 11:44
 */
@Controller
@RequestMapping("admin/wholesaler")
public class WholesalerController extends BaseController<YgWholesaler, Long> {

    @Autowired
    private YgWholesalerService ygWholesalerService;
    @Autowired
    private YgWholesalerRechargeRecordService ygWholesalerRechargeRecordService;
    @Autowired
    private SkuExcelHandler skuExcelHandler;
    @Autowired
    private YgWholesalerSkuService ygWholesalerSkuService;
    @Autowired
    private YgWholesalerPrebillRecordService ygWholesalerPrebillRecordService;
    @Autowired
    private WdtOrderExcelHandler wdtOrderExcelHandler;
    @Autowired
    private FileService fileService;
    @Autowired
    private RedisDao redisDao;

    /**
     * 查询
     *
     * @param queryInfo
     * @param wholesalerName
     * @return
     */
    @RequestMapping("search")
    @ResponseBody
    public Map<String, Object> search(QueryInfo queryInfo, String wholesalerName) {
        ResultSet<YgWholesaler> resultSet = ygWholesalerService.search(queryInfo, wholesalerName);
        return resultSet.toDatatables(null);
    }

    /**
     * 获取所有批发商
     *
     * @return
     */
    @RequestMapping("findList")
    @ResponseBody
    public Message findList() {
        return Message.success(ygWholesalerService.findList(null, null));
    }

    /**
     * 获取批发商信息
     *
     * @param id
     * @return
     */
    @RequestMapping("findById")
    @ResponseBody
    public Message findById(@RequestParam Long id) {
        return Message.success(ygWholesalerService.findById(id));
    }

    /**
     * 验证名称是否可用（true 可用，false 不可用）
     *
     * @param wholesalerName
     * @param id
     * @return
     */
    @RequestMapping("validateNameIsUsable")
    @ResponseBody
    public Message validateNameIsUsable(@RequestParam String wholesalerName, Long id) {
        return Message.success(ygWholesalerService.validateNameIsUsable(wholesalerName, id));
    }

    /**
     * 编辑
     *
     * @param wholesaler
     * @return
     */
    @RequestMapping("edit")
    @ResponseBody
    public Message edit(YgWholesaler wholesaler) {
        wholesaler.setUpdateTime(new Date());
        wholesaler.setUpdateBy(getSession().getTrueName());
        return ygWholesalerService.edit(wholesaler);
    }

    /**
     * 充值
     *
     * @param rechargeRecord
     * @return
     */
    @RequestMapping("recharge")
    @ResponseBody
    public Message recharge(YgWholesalerRechargeRecord rechargeRecord) {
        rechargeRecord.setCreateTime(new Date());
        rechargeRecord.setCreateBy(getSession().getTrueName());
        ygWholesalerRechargeRecordService.saveRechargeRecord(rechargeRecord);
        return Message.success(null);
    }

    /**
     * 充值记录查询
     *
     * @param queryInfo
     * @return
     */
    @RequestMapping("searchRechargeRecord")
    @ResponseBody
    public Map<String, Object> searchRechargeRecord(QueryInfo queryInfo, Long wholesalerId) {
        ResultSet<YgWholesalerRechargeRecord> resultSet = ygWholesalerRechargeRecordService.search(queryInfo, wholesalerId);
        return resultSet.toDatatables(null);
    }

    /**
     * 批发价列表
     *
     * @param queryInfo
     * @param wholesalerName
     * @param productName
     * @return
     */
    @RequestMapping("searchWholesaleSku")
    @ResponseBody
    public Map<String, Object> searchWholesaleSku(QueryInfo queryInfo, String wholesalerName, String productName) {
        ResultSet<WholesaleSkuModel> resultSet = ygWholesalerSkuService.search(queryInfo, wholesalerName, productName);
        return resultSet.toDatatables(null);
    }

    /**
     * 更新批发价
     *
     * @param id
     * @param wholesalePrice
     * @return
     */
    @RequestMapping("updateWholesalePrice")
    @ResponseBody
    public Message updateWholesalePrice(@RequestParam Long id, @RequestParam BigDecimal wholesalePrice) {
        YgWholesalerSku wholesalerSku = new YgWholesalerSku();
        wholesalerSku.setId(id);
        wholesalerSku.setWholesalePrice(wholesalePrice);
        wholesalerSku.setUpdateTime(new Date());
        wholesalerSku.setUpdateBy(getSession().getTrueName());
        ygWholesalerSkuService.update(wholesalerSku);
        return Message.success(null);
    }

    /**
     * 加载导入的SKU批发价数据
     *
     * @param uploadFile
     * @return
     */
    @RequestMapping(value = "loadExcelByWholesale", method = RequestMethod.POST)
    @ResponseBody
    public Message loadExcelByWholesale(@RequestParam("uploadFile") MultipartFile uploadFile) {
        List<Map<Integer, Object>> excelInfo;
        try {
            excelInfo = ExcelUtil.readExcel(uploadFile);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            return Message.error("读取导入数据错误", null);
        }
        return Message.success(skuExcelHandler.handlerExcelInfo(excelInfo, SkuExcelModel.SkuExcelType.SkuPrice));
    }

    /**
     * 批量保存批发价
     *
     * @param wholesalerId
     * @param skuWholesalePrices
     * @return
     */
    @RequestMapping("saveWholesalePrice")
    @ResponseBody
    public Message saveWholesalePrice(@RequestParam Long wholesalerId, @RequestParam String skuWholesalePrices) {
        List<YgWholesalerSku> list = JsonUtils.toObject(skuWholesalePrices, new TypeReference<List<YgWholesalerSku>>() {
        });
        ygWholesalerSkuService.saveWholesalePrice(list, wholesalerId, getSession().getTrueName());
        return Message.success(null);
    }

    /**
     * 预结列表
     *
     * @param wholesalerId
     * @param commitStatus
     * @return
     */
    @RequestMapping("findPrebillRecordList")
    @ResponseBody
    public Map<String, Object> findPrebillRecordList(@RequestParam Long wholesalerId, @RequestParam(defaultValue = "WaitingCommit") CommitStatus commitStatus) {
        List<YgWholesalerPrebillRecord> recordList = ygWholesalerPrebillRecordService.findListByWholesalerId(wholesalerId, commitStatus);
        if (CollectionUtils.isEmpty(recordList)) {
            return new ResultSet<>().toDatatables(null);
        }
        return new ResultSet<>(1, recordList).toDatatables(null);
    }

    /**
     * 提交预结单
     *
     * @param prebillCodes
     * @return
     */
    @RequestMapping("commitPrebillRecord")
    @ResponseBody
    public Message commitPrebillRecord(String[] prebillCodes) {
        if (prebillCodes == null || prebillCodes.length == 0) {
            return Message.error("请选择要提交的预接单", null);
        }
        ygWholesalerPrebillRecordService.commitPrebillRecord(Arrays.asList(prebillCodes), getSession().getTrueName());
        return Message.success(null);
    }

    /**
     * 导入旺店通原始单
     *
     * @param uploadFile 上传文件
     * @return
     */
    @RequestMapping("loadExcelByWDTOrder")
    @ResponseBody
    public Message loadExcelByWDTOrder(@RequestParam("uploadFile") MultipartFile uploadFile) {
        redisDao.del(RedisConstant.IMPORT_WDT_ORDER_WHOLESALE_PRICE.getBytes());
        Map<Integer, List<Row>> excelInfo;
        try {
            excelInfo = DocumentHandler.importExcel(uploadFile);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return Message.error("读取导入数据错误", null);
        }
        if (MapUtils.isEmpty(excelInfo)) {
            return Message.error("读取数据为空。", null);
        }
        Message message = wdtOrderExcelHandler.handlerExcelInfo(excelInfo);
        if (Message.isSuccess(message)) {
            redisDao.set(RedisConstant.IMPORT_WDT_ORDER_WHOLESALE_PRICE.getBytes(),
                    SerializeUtils.serialize(message.getExtra()), 24 * 60 * 60 * 1000);
        }
        return message;
    }

    /**
     * 导出旺店通原始单
     *
     * @param request  request
     * @param response response
     */
    @SuppressWarnings({"unchecked"})
    @RequestMapping("exportExcelByWDTOrder")
    public void exportExcelByWDTOrder(HttpServletRequest request, HttpServletResponse response) {
        byte[] value = redisDao.get(RedisConstant.IMPORT_WDT_ORDER_WHOLESALE_PRICE.getBytes());
        if (value == null || value.length == 0) {
            throw new IllegalArgumentException("请先导入旺店通订单数据");
        }
        List<WdtOrderImportExcelModel> detailList = (List<WdtOrderImportExcelModel>) SerializeUtils.deserialize(value);
        if (CollectionUtils.isEmpty(detailList)) {
            throw new IllegalArgumentException("请先导入旺店通订单数据");
        }
        byte[] bytes = fileService.downloadFromOss("template/export_wdt_order.xls");
        Map<String, Object> dataMap = new HashMap<>(1);
        dataMap.put("resultSet", detailList);
        DocumentHandler.DownloadExcel(bytes, "旺店通原始单.xls", dataMap, request, response);
        redisDao.del(RedisConstant.IMPORT_WDT_ORDER_WHOLESALE_PRICE.getBytes());
    }

    @RequestMapping("/findPlatformList")
    @ResponseBody
    public Message findPlatformList() {
        List<Map<String, String>> platformList = ygWholesalerService.findPlatformList();

        return Message.success(platformList);
    }

}
